package com.example.service;

import cn.hutool.json.JSONObject;
import com.example.common.Result;
import com.example.entity.*;
import com.example.entity.others.*;
import com.example.mapper.TeacherMapper;
import com.example.tool.QuestionGenerator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TeacherService {
    @Resource
    TeacherMapper teacherMapper;
    @Resource
    SparkService sparkService;
    @Resource
    QuestionGenerator questionGenerator;

    public List<JSONObject> testList(User_Subject userSubject) {
        List<Test_User> testUsers = teacherMapper.getTestUserListByUid(userSubject.getUid());
        List<JSONObject> tests = new ArrayList<>();
        for (Test_User testUser : testUsers) {
            JSONObject test = new JSONObject();
            test = teacherMapper.getTestById(testUser);
            if(test.get("subject") !=null && test.get("tname") !=null){
                if (userSubject.getSubject() == null && userSubject.getUname() == null){
                    tests.add(test);
                }else if(userSubject.getSubject() != null && userSubject.getUname() == null){
                    if(String.valueOf(test.get("subject")).equals(userSubject.getSubject())){
                        tests.add(test);
                    }
                }else if(userSubject.getSubject() == null && userSubject.getUname() != null){
                    if(String.valueOf(test.get("uname")).equals(userSubject.getUname())){
                        tests.add(test);
                    }
                }else {
                    if( String.valueOf(test.get("uname")).equals(userSubject.getUname()) && String.valueOf(test.get("subject")).equals(userSubject.getSubject())){
                        tests.add(test);
                    }
                }
            }
        }
        return tests;
    }

    public void createAi(Test_User_Other testUserOther) {
        Test test = testUserOther.getTest();
        User user = testUserOther.getUser();

        Test_User testUser = new Test_User();
        //插入test表
        teacherMapper.createTest(test);
        //插入test_user表
        testUser.setTid(test.getTid());
        testUser.setUid(user.getUid());
        teacherMapper.createTestUser(testUser);

        Map<String,List<Question>> allMap = questionGenerator.generateQuestionsConcurrently(test,user);

        for (String type : allMap.keySet()){
            List<Question> questionList = allMap.get(type);

            int i = 1;
            for (Question question : questionList){
                if(question.getContent() == null){
                    question.setContent(questionList.get(0).getContent());
                    question.setAnswer(questionList.get(0).getAnswer());
                    question.setKpoint(questionList.get(0).getKpoint());
                }
                question.setQnum(i);
                teacherMapper.createQuestion(question);

                Question_Teacher questionTeacher = new Question_Teacher();
                questionTeacher.setQid(question.getQid());
                questionTeacher.setTeaid(user.getUid());
                teacherMapper.createQuestionTeacher(questionTeacher);

                i++;
            }
        }
    }

    public Object questionAllTeacher(Test_User_Other testUserOther) {
        Map<String, List<User_Question>> map = new HashMap<>();

        List<User_Question> userQuestionC = teacherMapper.getUqcByTestidTeacher(testUserOther.getTest().getTid(), testUserOther.getUser().getUid());
        List<User_Question> userQuestionF = teacherMapper.getUqfByTestidTeacher(testUserOther.getTest().getTid(), testUserOther.getUser().getUid());
        List<User_Question> userQuestionS = teacherMapper.getUqsByTestidTeacher(testUserOther.getTest().getTid(), testUserOther.getUser().getUid());

        map.put("选择题", userQuestionC);
        map.put("填空题", userQuestionF);
        map.put("解答题", userQuestionS);

        return map;
    }

    public Object testDelete(Test_User testUser) {
        User user = new User();
        JSONObject json = teacherMapper.getTestById(testUser);
        Test test = new Test();
        test.setTid((Integer) json.get("tid"));
        test.setSubject((String) json.get("subject"));
        user.setUid(testUser.getUid());

        teacherMapper.deleteTestUser(testUser);
        List<Question> questions = teacherMapper.getAllByTid(test);
        for (Question question : questions) {
            Question_Teacher questionTeacher = new Question_Teacher();
            questionTeacher.setQid(question.getQid());
            questionTeacher.setTeaid(testUser.getUid());
            teacherMapper.deleteQuestion(questionTeacher);
        }
        User_Subject userSubject = new User_Subject();
        userSubject.setUid(testUser.getUid());
        userSubject.setSubject(test.getSubject());
        return this.testList(userSubject);
    }

    public void createHuman(Test_Map_Question testMapQuestion) {
        Question_Teacher questionTeacher = new Question_Teacher();
        Test test = new Test();

        List<Question> questionCAll = testMapQuestion.getQuestionMap().get("选择题");
        List<Question> questionFAll = testMapQuestion.getQuestionMap().get("填空题");
        List<Question> questionSAll = testMapQuestion.getQuestionMap().get("解答题");

        int i = 0;

        questionTeacher.setTeaid(testMapQuestion.getUser().getUid());
        test.setTid(testMapQuestion.getTest().getTid());

        for (Question question : questionCAll) {
            i++;
            question.setQnum(i);
            question.setTid(test.getTid());

            teacherMapper.createQuestion(question);
            questionTeacher.setQid(question.getQid());
            teacherMapper.createQuestionTeacher(questionTeacher);
        }

        test.setCnum(i);
        i = 0;

        for (Question question : questionFAll) {
            i++;
            question.setQnum(i);
            question.setTid(test.getTid());

            teacherMapper.createQuestion(question);
            questionTeacher.setQid(question.getQid());
            teacherMapper.createQuestionTeacher(questionTeacher);
        }

        test.setFnum(i);
        i = 0;

        for (Question question : questionSAll) {
            i++;
            question.setQnum(i);
            question.setTid(test.getTid());

            teacherMapper.createQuestion(question);
            questionTeacher.setQid(question.getQid());
            teacherMapper.createQuestionTeacher(questionTeacher);
        }

        test.setSnum(i);

        teacherMapper.updateTest(test);
    }

    public void doHomework(List<Question_Teacher> questionTeachers) {
        for (Question_Teacher qs : questionTeachers) {
            teacherMapper.updateQTById(qs);
        }
    }

    public Object createClass(Class_Teacher classTeacher) {
        Class_Teacher classTeacher1 = teacherMapper.getClassOneByteaid(classTeacher);
        if(classTeacher1==null){
            teacherMapper.createClass(classTeacher);
            teacherMapper.createClassTeacher(classTeacher);
        }else {
            classTeacher.setExist(1);
            classTeacher.setCid(classTeacher1.getCid());
            teacherMapper.updateClass(classTeacher);
        }
        return teacherMapper.getClassBytid(classTeacher);
    }

    public List<JSONObject> listClass(Class_Teacher classTeacher) {
        List<JSONObject> classList = teacherMapper.getClassBytid(classTeacher);
        return classList;
    }

    public Object cancelClass(Class_Teacher classTeacher) {
        classTeacher.setExist(0);
        teacherMapper.updateClass(classTeacher);
        return teacherMapper.getClassBytid(classTeacher);
    }

    public Object testListStudent(User_Subject userSubject) {
        List<Integer> classIds = teacherMapper.getclassIdsByTeaid(userSubject);
        if(userSubject.getCid() != 0){
            classIds = classIds.stream().filter(x -> x.equals(userSubject.getCid())).collect(Collectors.toList());
        }
        List<Integer> sidS = teacherMapper.getsIdsByclssiIds(classIds);
        List<JSONObject> tests = new ArrayList<>();
        for (Integer sid : sidS){
            User_Subject userSubjectS = new User_Subject();
            userSubjectS.setSubject(userSubject.getSubject());
            userSubjectS.setUname(userSubject.getUname());
            userSubjectS.setUid(sid);
            tests.addAll(this.testList(userSubjectS));
        }
        return tests;
    }

    public Object correctingAi(List<User_Question> userQuestions) {
        String input = "";
        int i = 0;
        for (User_Question userQuestion : userQuestions) {
            input = input + "QNum: " + userQuestion.getId() + "\n"
                    + "Question: " + userQuestion.getContent() + "\n"
                    + "Answer: " + userQuestion.getAnswer() + "\n"
                    + "UAnswer: " + userQuestion.getUanswer() + "\n";
            i++;
        }

        List<Question_Teacher> questionTeachers = sparkService.correctTeaQuestionAi(input, i);
        int teaid = userQuestions.get(0).getTeaid();
        for (Question_Teacher questionTeacher : questionTeachers) {
            questionTeacher.setTeaid(teaid);
            teacherMapper.updateQTByIdAi(questionTeacher);
        }


        Map<String, List<User_Question>> map = new HashMap<>();

        List<User_Question> userQuestionC = teacherMapper.getUqsByTestidTeacher(userQuestions.get(0).getTid(), userQuestions.get(0).getPid());
        List<User_Question> userQuestionF = teacherMapper.getUqfByTestidTeacher(userQuestions.get(0).getTid(), userQuestions.get(0).getPid());
        List<User_Question> userQuestionS = teacherMapper.getUqsByTestidTeacher(userQuestions.get(0).getTid(), userQuestions.get(0).getPid());


        map.put("选择题", userQuestionC);
        map.put("填空题", userQuestionF);
        map.put("解答题", userQuestionS);

        return map;
    }

    public void questionReset(int tid, int uid) {
        List<Integer> questionId = teacherMapper.getQuestionId(tid);
        for (Integer qid : questionId){
            teacherMapper.resetQuestion(uid,qid);
        }
    }

    public void setTest(Test_User testUser) {
        List<Integer> cidList = Collections.singletonList(testUser.getCid());
        List<Integer> uidList = new ArrayList<>();
        uidList = teacherMapper.getsIdsByclssiIds(cidList);
        for (Integer sid : uidList){
            Test_User test_user = new Test_User();
            test_user.setTid(testUser.getTid());
            test_user.setUid(sid);
            Test_User data = teacherMapper.getTestUserByTidUid(test_user);
            if(data == null){
                teacherMapper.createTestUser(test_user);
                List<Integer> questionList = teacherMapper.getQuestionId(test_user.getTid());
                for (Integer id : questionList){
                    Question_Student questionStudent = new Question_Student();
                    questionStudent.setSid(test_user.getUid());
                    questionStudent.setQid(id);
                    teacherMapper.createQuestionStudent(questionStudent);
                }
            }
        }
    }

    public List<JSONObject> createAnalysisBySubject(Analysis_Teacher analysisTeacher) {
        int aidname=teacherMapper.getAnameSubject(analysisTeacher) + 1;
        String aName=analysisTeacher.getSubject()+"分析"+aidname;

        analysisTeacher.setAname(aName);

        List<Integer> sids = teacherMapper.getsIdsByclssiIds(Collections.singletonList(analysisTeacher.getCid()));

        List<Test_User> testUsers = teacherMapper.getTestBySId(sids);

        Map<String, True_False_Num> map = new HashMap<>();

        for (Test_User test : testUsers) {
            String Kpoint = teacherMapper.gerKnpoint(test);
            True_False_Num trueFalseNum = new True_False_Num();

            int i = teacherMapper.getTrueCount(test.getUid(), test.getTid());
            int j = teacherMapper.getFalseCount(test.getUid(), test.getTid());

            trueFalseNum.setTNum(i);
            trueFalseNum.setFNum(j);

            map.compute(Kpoint, (key, existingValue) -> {
                if (existingValue == null) {
                    return trueFalseNum;
                } else {
                    existingValue.setTNum(existingValue.getTNum() + trueFalseNum.getTNum());
                    existingValue.setFNum(existingValue.getFNum() + trueFalseNum.getFNum());
                    return existingValue;
                }
            });
        }

        StringBuilder input = new StringBuilder(new String());

        for (String key : map.keySet()) {
            True_False_Num trueFalseNum = map.get(key);

            input.append("知识点: ").append(key).append("\n");
            input.append("错误数量: ").append(trueFalseNum.getFNum()).append("\n");
            input.append("正确数量: ").append(trueFalseNum.getTNum()).append("\n");
        }

        analysisTeacher.setContent(sparkService.correctAnalysisSubject(String.valueOf(input)));

        teacherMapper.createAnalysis(analysisTeacher);

        List<JSONObject> analysisTeachers=teacherMapper.getAnalysisList(analysisTeacher);

        return analysisTeachers;
    }

    public List<JSONObject> getAnalysisAll(Analysis_Teacher analysisTeacher) {
        return teacherMapper.getAnalysisList(analysisTeacher);
    }

    public Object deleteAnalysis(Analysis_Teacher analysisTeacher) {
        teacherMapper.deleteAnalysis(analysisTeacher);
        return teacherMapper.getAnalysisList(analysisTeacher);
    }

    public Object getAnalysis(Analysis_Teacher analysisTeacher) {
        return teacherMapper.getAnalysisContent(analysisTeacher.getAid());
    }

    public List<JSONObject> faultListStudent(JSONObject jsonObject) {
        User_Subject userSubject = new User_Subject();
        userSubject.setUid(jsonObject.getInt("uid"));
        List<Integer> cIds = teacherMapper.getclassIdsByTeaid(userSubject);
        if(jsonObject.get("cid")!=null){
            cIds = cIds.stream().filter(x -> x.equals(jsonObject.getInt("cid"))).collect(Collectors.toList());
        }
        List<Integer> sIds = teacherMapper.getsIdsByclssiIds(cIds);
        List<JSONObject> faultList = teacherMapper.getFaultList(sIds);
        if(jsonObject.get("cid")!=null){
            cIds = cIds.stream().filter(x -> x.equals(jsonObject.getInt("cid"))).collect(Collectors.toList());
        }
        if(jsonObject.get("subject")!=null){
            faultList = faultList.stream().filter(x -> Objects.equals(x.getStr("subject"), jsonObject.getStr("subject"))).collect(Collectors.toList());
        }
        if(jsonObject.get("knpoint")!=null){
            faultList = faultList.stream().filter(x -> Objects.equals(x.getStr("knpoint"), jsonObject.getStr("knpoint"))).collect(Collectors.toList());
        }
        return faultList;
    }
}
